package com.sl.core.engine.exchange;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.sl.core.engine.exchange.rest.RestApi;
import lombok.SneakyThrows;
import org.apache.camel.CamelContext;
import org.apache.camel.Route;
import org.apache.camel.impl.engine.AbstractCamelContext;

import java.util.List;

public class CamelConfig {

    public static final CamelConfig INSTANCE = new CamelConfig();

    private CamelContext camelContext;

    private ApiCallBackService apiCallBackService;

    @SneakyThrows
    public void init(CamelContext camelContext, ApiCallBackService apiCallBackService) {
        this.camelContext = camelContext;
        this.apiCallBackService = apiCallBackService;
        camelContext.addRoutes(new RestApi(apiCallBackService, null));
        List<Route> routes = camelContext.getRoutes();
    }

    @SneakyThrows
    public void changeApi(String baseRouteId) {

        if (ObjectUtil.isNull(camelContext)) {
            return;
        }
        this.removeApi(baseRouteId);
        //在新增一把
        camelContext.addRoutes(new RestApi(apiCallBackService, baseRouteId));


    }

    @SneakyThrows
    public void removeApi(String baseRouteId) {

        if (ObjectUtil.isNull(camelContext)) {
            return;
        }

        List<Route> routes = camelContext.getRoutes();


        for (Route route : routes) {
            String id = route.getId();
            if (StrUtil.contains( id,baseRouteId)) {
                if(camelContext instanceof AbstractCamelContext abs){
                    abs.stopRoute(id);
                }
                camelContext.removeRoute(id);
            }
        }
    }
}
